<?php
require_once __DIR__ . '/config.php';

class Database {
    private static $pdo;

    public static function getInstance() {
        if (!isset(self::$pdo)) {
            $dsn = 'mysql:host=' . DB_HOST . ';dbname=' . DB_NAME . ';charset=' . DB_CHARSET;
            $options = [
                PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
                PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
                PDO::ATTR_EMULATE_PREPARES   => false,
            ];
            try {
                self::$pdo = new PDO($dsn, DB_USER, DB_PASS, $options);
            } catch (\PDOException $e) {
                // 抛出带有详细诊断信息的异常
                $error_message = "数据库连接失败: " . $e->getMessage();
                if (strpos($e->getMessage(), 'Access denied for user') !== false) {
                    $error_message .= "。请检查 core/config.php 中的用户名和密码是否正确。";
                } elseif (strpos($e->getMessage(), 'Unknown database') !== false) {
                    $error_message .= "。请检查 core/config.php 中的数据库名称是否正确。";
                }
                throw new \PDOException($error_message, (int)$e->getCode());
            }
        }
        return self::$pdo;
    }
} 